import { CategoryAPI } from "@/api/CategoryAPI";
import type { Category } from "@/types/Category"
import type { Status } from "@/types/Status"
import { defineStore } from "pinia"
import type { Banner } from "@/types/Banner";
import { HomeAPI } from "@/api/HomeAPI";
import type { Goods, GoodsRequestParams } from "@/types/Goods";
import type { Pagination } from "@/types/Response";
//定义Store对象中状态的类型
type State = {
    categories: {
        //用于存储导航分类数据
        headerNav: (Category & { isOpen: boolean })[],
        status: Status,
        homeCategory: Category[]
    }
    // 轮播图
    banners: {
        result: Banner[];
        status: Status;
    };
    //一级分类具体信息
    topCategories: {
        result: {
            [id: string]: Category;
        };
        status: Status;
    }

    //二级分类筛选条件
    SubCategoryFilters: {
        result: {
            [id: string]: Category;
        };
        status: Status;
    }
    // 二级分类商品
    categoryGoods: {
        status: Status;
        result: Pagination<Goods>;
    };
}

//定义Getters对象的类型
type Getters = {
    //一级分类面包屑导航
    currentTop: (state: State) => (topCategoryId: string) => Category | undefined;
    //二级分类面包屑导航
    currentTopAndSub: (
        state: State
    ) => (
        topCategoryId: string,
        subCategoryId: string
    ) => { topCategory: Category | undefined; subCategory: Category | undefined }
}


//定义Actions对象的类型
type Actions = {
    getCategories(): Promise<void>
    toggle(id: string, isOpen: boolean): void
    // 获取轮播图
    getBanners(): Promise<void>;
    //根据一级分类id获取分类信息
    getTopCategoryById(id: string): Promise<void>
    //根据二级分类id获取该分类下的商品的筛选信息
    getSubCategoryFilters(id: string): Promise<void>
    // 获取二级分类商品
    getCategoryGoods(
        categoryId: GoodsRequestParams["categoryId"],
        reqParams?: Partial<Omit<GoodsRequestParams, "categoryId">>
    ): Promise<void>;
}

//创建categoryStore对象,返回用于获取categoryStore对象的方法
export const useCategoryStore = defineStore<"category", State, Getters, Actions>("category", {
    state: () => ({
        //用于存储导航分类列表数据
        categories: {
            headerNav: [],
            homeCategory: [],
            status: "idle"
        },
        banners: {
            result: [],
            status: "idle",
        },
        //一级分类信息
        topCategories: {
            result: {},
            status: "idle"
        },
        //二级分类筛选信息
        SubCategoryFilters: {
            result: {},
            status: 'idle'
        },
        // 二级分类商品
        categoryGoods: {
            result: {
                page: 0,
                pages: 0,
                pageSize: 0,
                counts: 0,
                items: [],
            },
            status: "idle",
        },
    }),
    getters: {
        //一级分类面包屑导航
        currentTop(state) {
            return function (topCategoryId) {
                return state.categories.headerNav.find(
                    (item) => item.id === topCategoryId
                )
            }
        },
        //二级分类面包屑导航
        currentTopAndSub(state) {
            return function (topCategoryId, subCategoryId) {
                const topCategory = state.categories.headerNav.find(
                    (item) => item.id === topCategoryId
                )
                const subCategory = topCategory?.children?.find(
                    (item) => item.id === subCategoryId
                )
                return { topCategory, subCategory }
            }
        }
    },
    actions: {
        //修改以及分类对象中的isOpen属性的值
        toggle(id, target) {
            //查找目标分类
            const category = this.categories.headerNav.find((category) => category.id === id)
            // 如果目标分类存在, 设置它的 isOpen 属性值为 target
            if (category) category.isOpen = target
        },
        //获用于获取导航分类列表数据
        async getCategories() {
            //记录请求状态
            this.categories.status = "loading";
            //捕获失败
            try {
                //发送请求 获取分类状态
                let response = await CategoryAPI.getCategories();
                //存储分类数据
                this.categories.headerNav = response.result.map((category) => ({
                    ...category,
                    isOpen: false
                }));
                //头部首页左侧分类列表
                this.categories.homeCategory = response.result.map((category) => ({
                    ...category,
                    children: category.children?.slice(0, 2)
                }))
                //记录请求状态
                this.categories.status = "success"
            } catch (error) {
                //记录请求状态
                this.categories.status = "error"
            }


        },
        // 获取轮播图
        async getBanners() {
            // 更新加载状态
            this.banners.status = "loading";
            // 捕获错误
            try {
                // 发送请求获取轮播图
                let response = await HomeAPI.getBanners(2);
                // 存储轮播图
                this.banners.result = response.result;
                // 更新加载状态
                this.banners.status = "success";
            } catch (e) {
                // 更新加载状态
                this.banners.status = "error";
            }
        },
        // 根据一级分类id获取分类信息
        async getTopCategoryById(id) {
            // 更新加载状态
            this.topCategories.status = "loading";
            // 捕获错误
            try {
                // 发送请求根据一级分类id获取分类信息
                let response = await CategoryAPI.getTopCategoryById(id);
                // 存储一级分类信息
                this.topCategories.result[response.result.id] = response.result;
                // 更新加载状态
                this.topCategories.status = "success";
            } catch (e) {
                // 更新加载状态
                this.topCategories.status = "error";
            }
        },
        // 根据二级分类id获取该分类下的商品的筛选信息
        async getSubCategoryFilters(id) {
            // 更新加载状态
            this.SubCategoryFilters.status = "loading";
            // 捕获错误
            try {
                // 发送请求根据二级分类id获取该分类下的商品的筛选信息
                let response = await CategoryAPI.getSubCategoryFilters(id);
                // 存储商品筛选信息
                this.SubCategoryFilters.result[response.result.id] = response.result;
                // 更新加载状态
                this.SubCategoryFilters.status = "success";
            } catch (e) {
                // 更新加载状态
                this.SubCategoryFilters.status = "error";
            }
        },
        // 获取二级分类商品
        async getCategoryGoods(categoryId, reqParams) {
            // 如果数据已经加载完成, 不再进行加载
            if (this.categoryGoods.status === "finished") return;
            // 更新加载状态
            this.categoryGoods.status = "loading";
            // 捕获错误
            try {
                // 发送请求获取二级分类商品数据
                let response = await CategoryAPI.getCategoryGoods(
                    categoryId,
                    reqParams
                );
                // 重新在本地存储分页数据以及商品数据
                if (reqParams?.page === 1) {
                    // 存储状态
                    this.categoryGoods.result = response.result;
                } else {
                    // 累加状态
                    this.categoryGoods.result = {
                        ...response.result,
                        items: [
                            ...this.categoryGoods.result.items,
                            ...response.result.items,
                        ],
                    };
                }
                // 如果当前请求页已经是最后一页或者服务端没有商品数据
                if (reqParams?.page === response.result.pages || response.result.pages === 0) {
                    // 更新加载状态
                    this.categoryGoods.status = "finished";
                } else {
                    // 更新加载状态
                    this.categoryGoods.status = "success";
                }
            } catch (e) {
                // 更新加载状态
                this.categoryGoods.status = "error";
            }
        },
    }
})